//
//  ALPlaceholderTextView.swift
//  Demo
//
//  Created by 柴瑞军 on 16/4/19.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit

class ALPlaceholderTextView: UITextView {

    //占位文本
    var placeholder:String?{
    
        didSet{
        
           placeholderLabel.text = placeholder
            
        }
    }
    
    override var text: String!{
        didSet{
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    override var font: UIFont?{
        didSet{
            placeholderLabel.font  = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        //placeholderLabel
        addSubview(placeholderLabel)
        //constraints
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ALPlaceholderTextView.didChangeText), name: UITextViewTextDidChangeNotification, object: self)
    }
    @objc private func didChangeText() {
        // 判断有没有文字
        placeholderLabel.hidden = hasText()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //显示placeholder的label
    private lazy var placeholderLabel:UILabel = {
    
        let label = UILabel()
        
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        
        label.text = "我是占位文本..."
        label.sizeToFit()

        
        return label
        
    }()
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
